// src/api/axios.js
import axios from 'axios';
import { showMessage } from '../utils/status'; // 引入状态码文件
import { ElMessage } from 'element-plus'; // 引入 el 提示框
import { useUserStore } from '../stores/useStore'; // 引入 Pinia store

// 创建 Axios 实例
const instance = axios.create({
  baseURL: '/api',
  timeout: 10000, // 设置请求超时时间
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    const token = userStore.token; // 获取动态 token

    // 配置请求头
    const headers = new axios.AxiosHeaders(config.headers);
    headers.setContentType('application/json;charset=UTF-8'); // 传参方式 json

    // 检查是否是登录接口
    const isLoginRequest = config.url === '/login'; // 判断请求路径是否为 /login

    // 如果不是登录接口且存在 token，则添加 Authorization 头
    if (!isLoginRequest && token) {
      headers.set('Authorization', `Bearer ${token}`); // 使用 Authorization 头传递 token
    }

    config.headers = headers;
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  response => {
    // 处理成功响应

    if(response.data.msg){
      ElMessage.success(response.data.msg);
    }

    return response.data;
  },
  error => {
    // 处理错误响应
    if (error.response) {
      const status = error.response.status;
      const message = showMessage(status) || error.response.data.msg;
      ElMessage.error(message);
    } else if (error.request) {
      ElMessage.error('没有任何响应.');
    } else {
      ElMessage.error('请求糟糕');
    }
    return Promise.reject(error);
  }
);

// 封装 GET POST 请求并导出
export function request(url = '', params = {}, type = 'POST', requiresAuth = true) {
  return new Promise((resolve, reject) => {
    let promise;
    if (type.toUpperCase() === 'GET') {
      promise = instance.get(url, { params, ...{ requiresAuth } });
    } else if (type.toUpperCase() === 'POST') {
      promise = instance.post(url, params, { ...{ requiresAuth } });
    } else if (type.toUpperCase() === 'PUT') {
      promise = instance.put(url, params, { ...{ requiresAuth } });
    } else if (type.toUpperCase() === 'PATCH') {
      promise = instance.patch(url, params, { ...{ requiresAuth } });
    } else if (type.toUpperCase() === 'DELETE') {
      promise = instance.delete(url, { params, ...{ requiresAuth } });
    }

    // 处理返回
    promise?.then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  });
}

// 导出不同 HTTP 方法
export const get = (url: string,params?: Record<string, any>,requiresAuth = true) => request(url, params, 'GET', requiresAuth);
export const post = (url: string, data = {}, requiresAuth = true) => request(url, data, 'POST', requiresAuth);
export const put = (url: string, data = {}, requiresAuth = true) => request(url, data, 'PUT', requiresAuth);
export const patch = (url: string, data = {}, requiresAuth = true) => request(url, data, 'PATCH', requiresAuth);
export const del = (url: string, params = {}, requiresAuth = true) => request(url, params, 'DELETE', requiresAuth);

export default instance;
